package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

//读写锁：读时共享，写时独占，写锁优先级比读锁高
var rwMutex sync.RWMutex
var value int

func main() {
	//播种随机数种子
	rand.Seed(time.Now().UnixNano())

	for i := 0; i < 5; i++ {
		go readGo(i+1)
	}
	for i := 0; i < 5; i++ {
		go writeGo(i+1)
	}
	for {
		;
	}
}

func readGo(idx int) {
	for {
		rwMutex.RLock() //以读模式加锁
		fmt.Printf("---%dth 读go程，读出：%d\n", idx, value)
		rwMutex.RUnlock()
	}
}

func writeGo(idx int) {
	for {
		//生成随机数
		num := rand.Intn(1000)

		rwMutex.Lock() //以写模式加锁
		value = num
		fmt.Printf("%dth写go程，写入：%d\n", idx, num)
		rwMutex.Unlock()
		//time.Sleep(time.Millisecond * 300)
	}
}
